package custom.base.ui.decoration;


import android.graphics.Rect;
import android.view.View;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import custom.base.ui.adapter.BaseRecyclerAdapter;


/**
 * Created by luozi on 2016/9/28.
 */
public class DecorationDividerGridItem extends RecyclerView.ItemDecoration {
    private int gap;
    private int leftSpace = 0, rightSpace = 0;
    private BaseRecyclerAdapter recyclerAdapter;

    public DecorationDividerGridItem(int gap, BaseRecyclerAdapter recyclerAdapter) {
        this(gap, recyclerAdapter, 0, 0);
    }

    public DecorationDividerGridItem(int gap, BaseRecyclerAdapter recyclerAdapter, int leftSpace, int rightSpace) {
        this.gap = gap;
        this.leftSpace = leftSpace;
        this.rightSpace = rightSpace;
        this.recyclerAdapter = recyclerAdapter;
    }

    /**
     * 左右两边的item间距不变，中间item左右减半
     */
    @Override
    public void getItemOffsets(Rect outRect, View view,
                               RecyclerView parent, RecyclerView.State state) {
        outRect.bottom = gap;
        int position = parent.getChildLayoutPosition(view);
        int span = ((GridLayoutManager) parent.getLayoutManager()).getSpanCount();
        // Add top margin only for the first item to avoid double gap between items
        if (position < recyclerAdapter.getHeadersCount()) {
            outRect.left = 0;
            outRect.right = 0;
        } else {
            int realP = position - recyclerAdapter.getHeadersCount();
            if (realP % span == 0) {//最左边的item
                outRect.left = leftSpace;
            }
            if (realP % span == (span - 1)) {//最右边的item
                outRect.right = rightSpace;
            } else {
                outRect.right = gap;
            }

        }
        outRect.top = 0;
    }
}